from io import BytesIO
import json

from django.conf import settings
from django.core.cache import cache
from django.http import HttpResponse
from django.shortcuts import redirect, reverse
from django.views.decorators.http import require_POST, require_GET
from django.contrib.auth import login, logout, authenticate, get_user_model

from apps.xfzauth.forms import SigninForm, SignupForm
from utils import restful
from utils.aliyunSms.aliyunsms import send_sms
from utils.captcha.captcha import Captcha


@require_POST
def signin_view(request):
    form = SigninForm(request.POST)
    if form.is_valid():
        telephone = form.cleaned_data.get('telephone')
        password = form.cleaned_data.get('password')
        remember = form.cleaned_data.get('remember')
        user = authenticate(request, username=telephone, password=password)
        if user:
            if user.is_active:
                login(request, user)
                if remember:
                    # None 默认2周
                    # 0 浏览器关闭
                    request.session.set_expiry(0)
                return restful.ok(message='登录成功~~')
            else:
                # 黑名单，未激活
                return restful.unauth_error()
        else:
            return restful.params_error(message='手机号码或者密码错误~~')
    else:
        errors = form.get_error()
        return restful.params_error(message=errors)


@require_POST
def signup_view(request):
    form = SignupForm(request.POST)
    if form.is_valid():
        telephone = form.cleaned_data.get('telephone')
        username = form.cleaned_data.get('username')
        password = form.cleaned_data.get('password')
        model_user = get_user_model()
        user = model_user.objects.create_user(telephone=telephone, username=username, password=password)
        return restful.ok(message='注册成功~~')
    else:
        errors = form.get_error()
        return restful.params_error(message=errors)


@require_GET
def logout_view(request):
    logout(request)
    return redirect(reverse('index'))


@require_GET
def img_captcha_view(request):
    """
    图形验证码:
        cache: img_uuid
    :param request:
    :return:
    """
    formid = request.GET.get('formid')
    text, img = Captcha.gene_code()
    cache.set(f'img_{formid}', text.lower(), settings.IMG_CAPTCHA_TIMEOUT)
    out = BytesIO()
    img.save(out, 'png')
    out.seek(0)
    response = HttpResponse(content_type='image/png')
    response.write(out.read())
    return response


@require_GET
def sms_captcha_view(request):
    """
    短信验证码:
        cache: sms_telephone
    :param request:
    :return:
    """
    telephone = request.GET.get('telephone', '')
    if not telephone or len(telephone) != 11:
        return restful.params_error(message='手机号码格式错误~~')
    code = Captcha.gene_number()
    # res = json.loads(send_sms(telephone, code).decode('utf-8'))
    print('*' * 20, code)
    res = {
        'Code': 'OK',
        'Message': 'MessageMessageMessage',
    }
    if res['Code'] == 'OK':
        cache.set(f'sms_{telephone}', code.lower(), settings.SMS_CAPTCHA_TIMEOUT)
        return restful.ok(message=res['Message'])
    return restful.params_error(message=res['Message'])
